package com.sq.util.web;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.URLDecoder;
import java.net.URLEncoder;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.sq.util.StringUtil;

public class NetUtil {

    private static final Logger log = LoggerFactory.getLogger(NetUtil.class);

    public static void checkPort(int port) {
        try {
            Socket socket = new Socket();
            socket.bind(new InetSocketAddress(port));
            socket.close();
        } catch (IOException e) {
            System.err.println("端口[" + port + "]被占用");
            e.printStackTrace();
            System.exit(0);
        }
    }

    public static String encode(String str) {
        return encode(str, "utf-8");
    }

    public static String encode(String str, String enc) {
        if (StringUtil.isBlank(str)) {
            return "";
        }
        try {
            return URLEncoder.encode(str, enc);
        } catch (UnsupportedEncodingException e) {
            log.error("编码[" + str + "]出错" + e.getMessage(), e);
            return str;
        }
    }

    public static String decode(String str) {
        return decode(str, "utf-8");
    }

    public static String decode(String str, String enc) {
        if (StringUtil.isBlank(str)) {
            return "";
        }
        try {
            return URLDecoder.decode(str, enc);
        } catch (UnsupportedEncodingException e) {
            log.error("解码[" + str + "]出错" + e.getMessage(), e);
            return str;
        }
    }
}
